<?php
defined('_VISIT_URL_') or exit('No direct script access allowed');

class tweet {

	protected $tweetPic = '';

	//微信公众号文章内容推选
	public function pushToTweet() {
		if (empty(getPost('infoid'))) {
			return util::getValidError('信息ID格式错误');
		}

		if (empty(getPost('title')) || valid::isWicked(getPost('title'))) {
			return util::getValidError('信息标题格式异常');
		}

		if (empty(getPost('sortation')) || valid::isWicked(getPost('sortation'))) {
			return util::getValidError('信息分类格式异常');
		}

		$rst = new sqlcon();

		$info = $rst->getInfo('id', 'tweet', "infoid = '" . getPost('infoid') . "' and sortation = '" . getPost('sortation') . "'");
		if (!empty($info)) {
			return util::getDataError('该信息已经推选过了');
		}

		//将信息保存在推选表
		$rst->addCollect('infoid', getPost('infoid'));
		$rst->addCollect('title', getPost('title'));
		$rst->addCollect('sortation', getPost('sortation'));
		$rst->addCollect('pushtime', date('Y-m-d H:i:s'));
		$rst->insertInfo('tweet');

		return util::getSuccess('success');
	}
	
	//获取推文的分类列表
	public function getSortationList() {
		$rst = new sqlcon();
		$list = $rst->getList('distinct sortation as text, sortation as value', 'tweet', 'id != 0');

		$result = util::getSuccess('success');
		$result['sortationList'] = $list;

		return $result;
	}

	//获取推文信息列表
	public function getTweetList() {
		$sortation = getPost('sortationInfo');
		$page = getPost('page', '1');
		$permission = getPost('permission');

		$queryitem = '';
		if ($sortation != '')
			$queryitem .= " and sortation = '" . $sortation . "'";

		$limititem = ' limit ' . ($page - 1) * 50 . ', 50';
		$sortOption = 'pushtime desc, id desc';

		$rst = new sqlcon();

		$info = $rst->getInfo('count(*) as num', 'tweet', 'id != 0' . $queryitem);

		$list = $rst->getList('infoid, title, sortation, pushtime', 'tweet', 'id != 0' . $queryitem, $sortOption . $limititem);

		$result = util::getSuccess('success');
	    $result['listCount'] = $info['num'];
	    $result['allPages'] = util::getListPage($info['num'], 50);
	    $result['tweetList'] = $list;
	    $result['rowCount'] = 50;
	    if ($permission == 'yes') {
	    	$result['permission'] = util::getOperateItem(getPost('menuid'));
	    }
		return $result;
	}

	//删除一条推文信息
	public function deleteInfo() {
		if (empty(getPost('infoid'))) {
			return util::getValidError('ID格式错误');
		}

		$rst = new sqlcon();

		$rst->addCollect('infoid', getPost('infoid'));
        $rst->deleteInfo('tweet');

        return util::getSuccess('success');
	}

	//删除全部推文信息
	public function deleteAllInfo() {
		$rst = new sqlcon();

		$rst->setSql('delete from tweet where id != 0');
        $rst->execute();

        return util::getSuccess('success');
	}

	//生成推文的Html
	public function createTweetHtml() {
		if (empty(getPost('sortation'))) {
			return util::getValidError('请确定推文的分类');
		}

		$rst = new sqlcon();
		$sortationList = explode('、', getPost('sortation'));
		$this->tweetPic = array();
		$html = '';
		$downloadUrl = '';

		for ($i = 0; $i < count($sortationList); $i++) {
			$idList = $rst->getList('infoid', 'tweet', "sortation = '" . $sortationList[$i] . "'", 'id asc');
			$html .= $this->assembleContentHtml($idList, $sortationList[$i]);
		}

		$html .= '<p ><br/></p><p ><br/></p><p ><br/></p><section>
			<p style="text-align:center;" align="center">
				<span style="font-size: 15px; color: #ff0000;">长按二维码关注【生活宝】公众号</span>
			</p>
			<p style="text-align:center;" align="center">
				<span style="font-size: 15px; color: #ff0000;">直接获取更多日常生活服务信息</span><span style="font-size:14px;"> </span>
			</p>
			<p style="text-align:center;" align="center">
				<img src="" style="vertical-align: inherit; width: 50%; height: auto;box-sizing:border-box;max-width:50% !important;" alt="" width="50%" data-width="50%" data-ratio="1" data-w="400"/>
			</p>
			<p style="text-align:center;" align="center">
				<br/>
			</p>
			</section><section data-tools="135编辑器" data-id="123004" class="_135editor">
				<section style="margin: 10px auto;transform-style: preserve-3d;">
					<section style="max-width: 100% !important;width: 100%;box-sizing:border-box;transform: translateZ(5px);-webkit-transform: translateZ(5px);-moz-transform: translateZ(5px);-o-transform: translateZ(5px);" data-width="100%">
						<span style="color: #3f3f3f; font-size: 14px; letter-spacing: 1.5px; text-align: justify; caret-color: red;"></span>
					</section>
				</section>
				<p style="line-height: 1.75em;text-align:center;" align="center">
					<span style="font-size:16px;"><strong><span style="color: #316589;">END</span></strong></span>
				</p>
			</section>';

		//有相关联的图片需要拷贝+压缩，并下载
		if (!empty($this->tweetPic)) {
			//先将 tweet 文件夹内的图片与压缩包清空
			$folderPath = _FILE_PATH_ . 'upload/tweet/';
			if (is_dir($folderPath)) {
				if ($dh = opendir($folderPath)) {
					while (($file = readdir($dh)) !== false) {
						if ($file != '.' && $file != '..') {
							util::deleteFile($folderPath . $file);
						}
					}
					closedir($dh);
				}
			}

			//生成一个空的压缩包，生成压缩包的下载url
			$zipName = 'upload/tweet/' . time() . '.zip';
			$zipPath = _FILE_PATH_ . $zipName;
			$downloadUrl = _HTTP_PATH_ . $zipName;
			$destinationFile = _FILE_PATH_ . 'upload/tweet/';

			$zip = new ZipArchive();
			$zip->open($zipPath, ZipArchive::CREATE);

			//再将收集到的图片按路径复制到 tweet 文件夹，按信息标题改名，且将其加入压缩包
			for ($i = 0; $i < count($this->tweetPic); $i++) {
				if (file_exists($this->tweetPic[$i]['path'])) {
					$newPath = $destinationFile . $this->tweetPic[$i]['name'];
					copy($this->tweetPic[$i]['path'], $newPath);

					$zip->addFile($newPath, basename($newPath));
				}
			}

			//压缩包操作一定要关闭
			$zip->close();
		}

		$result = util::getSuccess('success');
	    $result['html'] = $html;
	    $result['zipurl'] = $downloadUrl;
		return $result;
	}

	//组装单个分类的推文内容html
	protected function assembleContentHtml($idList, $sortation) {
		$rst = new sqlcon();
		$html = '';
		$table = '';
		$field = '';
		if ($sortation == '家电维修') {
			$table = 'electronic a, tweet b';
			$field = 'a.title, a.address, a.person, a.phone, a.category, a.feature, a.area, a.smallpic';
			$where = 'a.electronicid = b.infoid and a.status = 1';
		}
		else if ($sortation == '家政服务') {
			$table = 'housecraft a, tweet b';
			$field = 'a.title, a.sortation, a.address, a.person, a.phone, a.identity, a.feature, a.area, a.smallpic';
			$where = 'a.housecraftid = b.infoid and a.status = 1';
		}
		else {
			$table = 'other a, tweet b';
			$field = 'a.title, a.address, a.person, a.phone, a.feature, a.area, a.smallpic';
			$where = "a.sortation = '" . $sortation . "' and a.otherid = b.infoid and a.status = 1";
		}

		//推文内容的头部（显示分类）
		$html .= '<section style="box-sizing: border-box;margin: 0px 10px;">
			<section class="_135editor" data-role="title" data-tools="135编辑器" data-id="125054">
				<section data-role="title" data-tools="135编辑器" data-id="125054" style="margin: 20px 0px;box-sizing: border-box;" class="_135editor">
					<section style="margin: 10px auto;">
						<section style="display: flex;justify-content: center;padding: 10px 0px 0px;box-sizing: border-box;" class="">
							<section style="transform-style: preserve-3d;">
								<section style="margin-top: -10px;transform: translateZ(12px);-webkit-transform: translateZ(12px);-moz-transform: translateZ(12px);-o-transform: translateZ(12px);" class="">
									<p style="font-size: 16px;color: #ffffff;letter-spacing: 1.5px;background: linear-gradient(to right,#ff6400,#ff6400);padding: 6px 20px;box-sizing: border-box;text-align:center;" align="center">
										' . $sortation . '
									</p>
									<section style="width: 80%;background-color: #fec134;height: 6px;margin: -3px auto 0;box-sizing:border-box;max-width:80% !important;" data-width="80%" class="">
										<br/>
									</section>
								</section>
							</section>
						</section>
					</section>
				</section>
			</section>
			<section class="_135editor">
				<section style="line-height: 30.75px;text-align: justify;font-size: 14px;letter-spacing: 1.5px;color: #3f3f3f;" class="135brush" data-autoskip="1">';

		$list = $rst->getList($field, $table, $where, 'a.sort desc');
		for ($i = 0; $i < count($list); $i++) {
			$html .= '<p style="line-height:1.75em"><strong><span style="font-size: 16px; letter-spacing: 1.5px; color: #000000;">' . ($i + 1) . '、' . $list[$i]['title'] . '</span></strong></p>';
			$html .= '<section class="_135editor" data-tools="135编辑器" data-id="125443"><section style="margin: 10px auto;"><section style="border: 1px solid #ff6400; padding: 18px; box-sizing: border-box;" class="">';

			if (!empty($list[$i]['address'])) {
				$html .= '<div style="margin-bottom: 10px; box-sizing: border-box; padding: 0px; line-height: 1.25em;">商家地址：' . $list[$i]['address'] . '</div>';
			}
			if ($sortation == '家政服务' && $list[$i]['sortation'] == '0') {
				$html .= '<div style="margin-bottom: 10px; box-sizing: border-box; padding: 0px; line-height: 1.25em;">服务提供方：' . ($list[$i]['identity'] == '0' ? '个人' : '家政公司') . '</div>';
			}
			if (!empty($list[$i]['category'])) {
				$html .= '<div style="margin-bottom: 10px; box-sizing: border-box; padding: 0px; line-height: 1.25em;">服务项目：' . $list[$i]['category'] . '</div>';
			}
			if (!empty($list[$i]['feature'])) {
				$html .= '<div style="margin-bottom: 10px; box-sizing: border-box; padding: 0px; line-height: 1.25em;">服务特征：' . $list[$i]['feature'] . '</div>';
			}
			if (!empty($list[$i]['area'])) {
				$html .= '<div style="margin-bottom: 10px; box-sizing: border-box; padding: 0px; line-height: 1.25em;">服务范围：' . $list[$i]['area'] . '</div>';
			}
			if (!empty($list[$i]['person'])) {
				$html .= '<div style="margin-bottom: 10px; box-sizing: border-box; padding: 0px; line-height: 1.25em;">联系人：' . $list[$i]['person'] . '</div>';
			}
			if (!empty($list[$i]['phone'])) {
				$html .= '<div style="margin-bottom: 10px; box-sizing: border-box; padding: 0px; line-height: 1.25em;">联系电话：' . $list[$i]['phone'] . '</div>';
			}
			if (!empty($list[$i]['smallpic'])) {
				$html .= '<img src="" style="vertical-align: inherit; width: 100%;box-sizing:border-box;max-width:100% !important;" draggable="false" />';

				$pic = array();
				$pic['name'] = $list[$i]['title'] . '.' . explode('.', $list[$i]['smallpic'])[1];
				$pic['path'] = _IMGS_PATH_ . $list[$i]['smallpic'];
				$this->tweetPic[] = $pic;
			}

			$html .= '</section></section></section>';

			if ($i < count($list) - 1) {
				$html .= '<p style="line-height:1.75em"><br/></p>';
			}
		}

		$html .= '</section></section></section><br/>';

		return $html;
	}

}